//Create by zhongxiang.huang
$(function () {
    
    $MB.initTpvMeetingElement();
    var $browserPluginableForm = $(".android-app-table-form");
    $("#input-file").prop("accept",".apk")

    var settings = {
        url: ctx + "appupdate/list/1",
        pageSize: 10,
        clickToSelect: false,
        queryParams: function (params) {
            var startDate =$("input[name='app-filter-start-date-link']").val();
            var endDate = $("input[name='app-filter-end-date-link']").val();

            var hasStartDateSelected = startDate != '';
            var hasEndDateSelected = endDate != '';

            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                startDate: (hasStartDateSelected ? new Date(startDate) : undefined),
                endDate: (hasEndDateSelected ? new Date(endDate) : undefined),
            };
        },
        columns: [{
            checkbox: true
        }, {
            field: 'id',
            visible: false
        }, {
            field: 'name',
            title: 'name',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }
        }, {
            field: 'packageName',
            title: 'packageName',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }
        }, {
            field: 'versionName',
            title: 'versionName',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }
        }, {
            field: 'versionCode',
            title: 'versionCode',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }
        },{
            field: 'fileSize',
            title: 'fileSize',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }            
        }, {
            field: 'publishTime',
            title: 'publishTime',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }            
        }, {
            field: 'downPath',
            title: 'downPath',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }            
        }]
    };

    $MB.initTable('AndroidAppTable', settings);

    $("#file-upload .start-upload").click(function () {
    	var inputfile = document.getElementById("input-file").files;
    	var fileName = inputfile[0].name;
    	var ext = fileName.slice(fileName.lastIndexOf(".")+1).toLowerCase();
    	if("apk" === ext){
    		$("#result").text("正在上传");
    	    var form = $('#fileUploadForm')[0];
    	    var data = new FormData(form);
    	    $.ajax({
    	        type: "POST",
    	        enctype: 'multipart/form-data',
    	        url: "appupdate/upload",
    	        data: data,
    	        //http://api.jquery.com/jQuery.ajax/
    	        //http://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
    	        processData: false, //prevent jQuery from automatically transforming the data into a query string
    	        contentType: false,
    	        cache: false,
    	        timeout: 600000,
    	        success: function (data) {

    	            $("#result").text(data.msg);
    	            $("#file-infor").show();
    	            if (data.code === "success") {
    	            	$("#version-name").val(data.versionName);
    	 	            $("#version-code").val(data.versionCode);
    	 	            $("#package-name").val(data.package);
    				}else{
    					$("#version-name").val("");
    	 	            $("#version-code").val("");
    	 	            $("#package-name").val("");
    					$("#apk-result").text(data.error);
    				}
    	            //console.log("SUCCESS : ", data);
    	        },
    	        error: function (e) {
    	            $("#result").text(e.responseText);
    	            console.log("ERROR : ", e);
    	        }
    	    });
    	}else{
    		$("#result").text("文件类型不正确");
    	}          
   });
	
	$("#file-upload .finish").click(function () {
		var inputfile = document.getElementById("input-file").files;
		var packageName = $("input[name='packageName']").val();
		var versionName = $("input[name='versionName']").val();
		var versionCode = $("input[name='versionCode']").val();
		var publishStatus = $("select[name='publishStatus']").val();
		var data = {
            "name": inputfile[0].name,
            "fileSize":formatFileSize(inputfile[0].size),
            "fileType":1,
            "packageName":packageName,
            "versionName":versionName,
            "versionCode":versionCode,
            "publishStatus":publishStatus
        };

		$(this).attr("disabled",true);
        $.post(ctx + "appupdate/add", data, function (r) {
            if (r.code === 0) {
                closeModal();
                $MB.n_success(r.msg);
                $MB.refreshTable("AndroidAppTable");
            } else {
                $MB.n_danger(r.msg);
            }
            $("#file-upload .finish").removeAttr("disabled");
        });
       
	});
	
	$("#app-edit .finish").click(function () {
		var appId = $("#appEditForm").attr("app-id");
		var packageName = $("#edit-package-name").val();
		var versionName = $("#edit-version-name").val();
		var versionCode = $("#edit-version-code").val();
		$(this).attr("disabled",true);
		
		var data = {
			"fileType":1,
            "packageName": packageName,
            "versionName": versionName,
            "versionCode": versionCode
        };
		
		$.post(ctx + "appupdate/edit/" + appId, data, function (r) {
            if (r.code === 0) {
            	$MB.closeAndRestModal("app-edit");
            	$("#app-edit .finish").removeAttr("disabled");
                $MB.n_success(r.msg);
                $MB.refreshTable("AndroidAppTable");
            } else {
                $MB.n_danger(r.msg);
            }
            	
            $("#app-edit .finish").removeAttr("disabled");
        });
	});

    $("#app-filter-start-date").on("change", search);
    $("#app-filter-end-date").on("change", search);
});

function writeObj(obj){ 
    var description = ""; 
    for(var i in obj){ 
        var property=obj[i]; 
        description+=i+" = "+property+"\n"; 
    } 
    console.log("*******************writeObj***************"+description);
}

function addNewVersion(){
	var $form = $('#file-upload');
    $form.modal();
}

function edit() {
    var selected = $("#AndroidAppTable").bootstrapTable('getSelections');
    var selected_length = selected.length;

    if(!selected_length) {
        $MB.n_warning("请选择要编辑的应用");
        return;
    }
    if(selected_length > 1) {
        $MB.n_warning("只支持单个应用编辑");
        return;
    }

    doEtit(selected[0].id);
}

function doEtit(appId){
	$.get(ctx + "appupdate/edit/" + appId, function(r) {
        if(r.code == 0) { 
        	var app = r.msg;

            $appEditForm = $("#appEditForm")
            $appEditForm.attr("app-id", app.id);
            
            $("#edit-version-name").val(app.versionName);
            $("#edit-version-code").val(app.versionCode);
            $("#edit-package-name").val(app.packageName);
            $('#app-edit').modal();
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function downLoadPlugin(){
	var selected = $("#AndroidAppTable").bootstrapTable('getSelections');
    var selected_length = selected.length;

    if(!selected_length) {
        //$MB.n_warning($MB.i18n('meeting.tips.edit.select.none'));
    	$MB.n_warning("请选择要下架的插件");
        return;
    }
}

function search() {
    $MB.refreshTable('AndroidAppTable');
}


function refresh() {
    $(".android-app-table-form input[type=hidden]").val('');
    $(".android-app-table-form")[0].reset();

    $MB.refreshTable('AndroidAppTable');
}

function closeModal() {
	$("#input-file").val('');
	$("#result").text("");
	$("#file-infor").hide();
	$("#apk-result").text("");
    $("#file-upload .finish").removeAttr("disabled");
    $MB.closeAndRestModal("file-upload");
}

function formatFileSize(fileSize) {
    if (fileSize < 1024) {
        return fileSize + 'B';
    } else if (fileSize < (1024*1024)) {
        var temp = fileSize / 1024;
        temp = temp.toFixed(2);
        return temp + 'KB';
    } else if (fileSize < (1024*1024*1024)) {
        var temp = fileSize / (1024*1024);
        temp = temp.toFixed(2);
        return temp + 'MB';
    } else {
        var temp = fileSize / (1024*1024*1024);
        temp = temp.toFixed(2);
        return temp + 'GB';
    }
}


